package com.milo.java8.optional;

import com.milo.java8.optional.entity.Cookie;
import org.junit.Test;

import java.util.Arrays;
import java.util.Optional;

/**
 * @author milogenius
 * @date 2020-06-09 17:28
 */
public class FlatMapTest {

    @Test
    public void test1(){
        Cookie a = new Cookie("a", "1");
        Cookie b = new Cookie("b", "1");
        Cookie c = new Cookie("c", "1");
        final Cookie[] maybeCookies = {a,b,c};
        if (maybeCookies != null) {
            for (int i = 0; i < maybeCookies.length; i++) {
                final Cookie cookie = maybeCookies[i];
                if ("a".equals(cookie.getName())) {
                    String value = cookie.getValue();
                    System.out.println(value);
                }
            }
        }
    }

    @Test
    public void test2(){
        Cookie a = new Cookie("a", "1");
        Cookie b = new Cookie("b", "1");
        Cookie c = new Cookie("c", "1");
        final Cookie[] maybeCookies = {a,b,c};
        if (maybeCookies != null) {
            Optional<Cookie> cookie = Arrays.stream(maybeCookies).
                    filter(e -> "a".equals(e.getName())).
                    findAny();
            String s = cookie.isPresent() ? cookie.get().getValue() : null;
            System.out.println(s);
        }
    }

    @Test
    public void test3(){
        Cookie a = new Cookie("a", "1");
        Cookie b = new Cookie("b", "1");
        Cookie c = new Cookie("c", "1");
        final Cookie[] maybeCookies = {a,b,c};
        String s = Optional.ofNullable(maybeCookies)
                .flatMap(cookies -> Arrays.stream(cookies)
                        //寻找我们需要的cookie
                        .filter(e -> "a".equals(e.getName()))
                        .findAny()
                )
                //如果匹配到,返回这个值
                .map(e -> e.getValue())
                //如果没有匹配到,返回null
                .orElse(null);
        System.out.println(s);
    }

    @Test
    public void test4(){
        Cookie a = new Cookie("a", "1");
        Cookie b = new Cookie("b", "1");
        Cookie c = new Cookie("c", "1");
        final Cookie[] maybeCookies = {a,b,c};
        String a1 = getCookieValue("a", maybeCookies).orElse(null);
        System.out.println(a1);

    }

    public Optional<String> getCookieValue(String name,Cookie[] cookies) {
        if (cookies == null) {
            return Optional.empty();
        }
        return Arrays.stream(cookies)
                .filter(e -> name.equals(e.getName()))
                .findAny().map(Cookie::getValue);
    }


}
